package com.example.sprintboot.controller;

import com.example.sprintboot.entity.Order;
import com.example.sprintboot.entity.Product;
import com.example.sprintboot.security.UserDetailsImpl;
import com.example.sprintboot.service.OrderService;
import com.example.sprintboot.service.ProductService;
import com.example.sprintboot.vo.OrderDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/seller")
public class SellerController {

    @Autowired
    private ProductService productService;

    @Autowired
    private OrderService orderService;

    // 获取当前登录用户ID
    private Integer getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetailsImpl) {
            return ((UserDetailsImpl) authentication.getPrincipal()).getUserId();
        }
        return null;
    }

    // 获取卖家的商品列表
    @GetMapping("/products")
    public Map<String, Object> getSellerProducts() {
        Integer sellerId = getCurrentUserId();
        if (sellerId == null) {
            return error("用户未登录");
        }
        List<Product> products = productService.getProductsBySellerId(sellerId);
        return success("查询成功", products);
    }

    // 获取卖家的订单列表
    @GetMapping("/orders")
    public Map<String, Object> getSellerOrders() {
        Integer sellerId = getCurrentUserId();
        if (sellerId == null) {
            return error("用户未登录");
        }
        List<Order> orders = orderService.getOrdersBySellerId(sellerId);
        return success("查询成功", orders);
    }

    // 获取卖家订单详情
    @GetMapping("/orders/{orderId}")
    public Map<String, Object> getSellerOrderDetail(@PathVariable Integer orderId) {
        Integer sellerId = getCurrentUserId();
        if (sellerId == null) {
            return error("用户未登录");
        }
        OrderDetailVO vo = orderService.getOrderDetailVO(orderId, sellerId);
        if (vo == null) {
            return error("订单不存在或无权限");
        }
        return success("查询成功", vo);
    }

    // 卖家发货
    @PostMapping("/orders/{orderId}/ship")
    public Map<String, Object> shipOrder(@PathVariable Integer orderId) {
        Integer sellerId = getCurrentUserId();
        if (sellerId == null) {
            return error("用户未登录");
        }
        boolean ok = orderService.shipOrder(sellerId, orderId);
        if (ok) {
            return success("发货成功", null);
        } else {
            return error("发货失败");
        }
    }

    // 获取卖家统计数据
    @GetMapping("/stats")
    public Map<String, Object> getSellerStats() {
        Integer sellerId = getCurrentUserId();
        if (sellerId == null) {
            return error("用户未登录");
        }
        
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalProducts", productService.getProductCountBySellerId(sellerId));
        stats.put("totalOrders", orderService.getOrderCountBySellerId(sellerId));
        stats.put("totalRevenue", orderService.getTotalRevenueBySellerId(sellerId));
        stats.put("pendingOrders", orderService.getPendingOrderCountBySellerId(sellerId));
        
        return success("查询成功", stats);
    }

    // 更新商品状态（上架/下架）
    @PutMapping("/products/{productId}/status")
    public Map<String, Object> updateProductStatus(@PathVariable Integer productId, 
                                                   @RequestBody Map<String, String> req) {
        Integer sellerId = getCurrentUserId();
        if (sellerId == null) {
            return error("用户未登录");
        }
        
        String status = req.get("status");
        if (status == null) {
            return error("状态参数不能为空");
        }
        
        boolean ok = productService.updateProductStatus(productId, sellerId, status);
        if (ok) {
            return success("状态更新成功", null);
        } else {
            return error("状态更新失败");
        }
    }

    // 新增商品（卖家）
    @PostMapping("/products")
    public Map<String, Object> addProduct(@RequestBody Product product) {
        Integer sellerId = getCurrentUserId();
        if (sellerId == null) {
            return error("用户未登录");
        }
        // 角色判断（可选，已由SecurityConfig控制）
        boolean success = productService.addProduct(product, sellerId, "seller");
        return success("商品发布" + (success ? "成功" : "失败"), null);
    }

    // 编辑商品
    @PutMapping("/products/{productId}")
    public Map<String, Object> updateProduct(@PathVariable Integer productId, @RequestBody Product product) {
        Integer sellerId = getCurrentUserId();
        if (sellerId == null) {
            return error("用户未登录");
        }
        product.setProductId(productId);
        boolean ok = productService.updateProduct(product, sellerId, "seller");
        if (ok) {
            return success("商品更新成功", null);
        } else {
            return error("商品更新失败");
        }
    }

    // 删除商品
    @DeleteMapping("/products/{productId}")
    public Map<String, Object> deleteProduct(@PathVariable Integer productId) {
        Integer sellerId = getCurrentUserId();
        if (sellerId == null) {
            return error("用户未登录");
        }
        boolean ok = productService.deleteProduct(productId, sellerId, "seller");
        if (ok) {
            return success("商品删除成功", null);
        } else {
            return error("商品删除失败");
        }
    }

    private Map<String, Object> success(String msg, Object data) {
        Map<String, Object> map = new HashMap<>();
        map.put("success", true);
        map.put("message", msg);
        map.put("data", data);
        return map;
    }

    private Map<String, Object> error(String msg) {
        Map<String, Object> map = new HashMap<>();
        map.put("success", false);
        map.put("message", msg);
        return map;
    }
} 